//
//  OAuthViewController.swift
//  新浪weibo
//
//  Created by test on 15/7/31.
//  Copyright © 2015年 test. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController,UIWebViewDelegate {
    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
    }
    
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        webView.delegate = self
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedNetworkTools.oauthUrl()))

    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        //Mark
        if !urlString.hasPrefix(NetworkTools.sharedNetworkTools.redirectUri) {
            
            return true
        }
        
        if let query = request.URL?.query where query.hasPrefix("code=")
        {
            let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
            
            loadAccessToken(code)
            
        } else {
            close()
            
        }
  
        return true
    }
    
    private func loadAccessToken(code:String) {
        NetworkTools.sharedNetworkTools.loadAccessToken(code) { (result, error) -> () in
            print(result)
            if result == nil || error != nil {
                self.netError()
                
                  return
            }
          
            let account = UserAccount(dict: result!)
            account.saveAccount()
            
            print(account)
            
        }
        
        
    }
    
    private func netError() {
        SVProgressHUD.showInfoWithStatus("网络不给力")
        
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue()) { () -> Void in
            self.close()
        }
        
    }
    
}
